<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';

import {
  createUniver,
  defaultTheme,
  FUniver,
  LocaleType,
  merge,
  Univer,
} from '@univerjs/presets';
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
import UniverPresetSheetsCoreEnUS from '@univerjs/presets/preset-sheets-core/locales/en-US';
import { ElMessage } from 'element-plus';
import mapboxgl from 'mapbox-gl';
import * as xlsx from 'xlsx';

import 'mapbox-gl/dist/mapbox-gl.css';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';

let mapInstance: mapboxgl.Map | null = null;

const container = ref<HTMLElement | null>(null);
const leftPanelWidth = ref(window.innerWidth / 2);
const isDragging = ref(false);
const startX = ref(0);
const mapContainer = ref<HTMLElement | null>(null); // 地图容器

let univerInstance: null | Univer = null;
let univerAPIInstance: FUniver | null = null;

onBeforeUnmount(() => {
  univerInstance?.dispose();
  univerAPIInstance?.dispose();
  univerInstance = null;
  univerAPIInstance = null;
});

// 导入文件函数
const importFile = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (!input.files || input.files.length === 0) return;

  const file = input.files[0];
  const reader = new FileReader();

  reader.addEventListener('load', async (e) => {
    try {
      if (!univerAPIInstance) {
        console.error('univerAPIInstance is null');
        return;
      }

      const data = e.target?.result;
      if (!data) {
        console.error('File data is empty');
        return;
      }

      let workbookData;
      try {
        if (file.name.endsWith('.csv')) {
          workbookData = xlsx.read(data as string, { type: 'string' });
        } else if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
          workbookData = xlsx.read(data as ArrayBuffer, { type: 'array' });
        } else {
          ElMessage.error('不支持的文件格式。');
          return;
        }
      } catch {
        ElMessage.error('读取文件失败，请确认文件是否受损或格式正确。');
        return;
      }

      univerAPIInstance.createWorkbook({
        name: '导入数据',
        worksheetCount: 0,
      });

      const workbook = univerAPIInstance.getActiveWorkbook();
      if (!workbook || typeof workbook.getSheets !== 'function') {
        console.error('获取新工作簿失败或API不兼容');
        return;
      }

      for (const sheetName of workbookData.SheetNames) {
        try {
          const rawSheet = workbookData.Sheets[sheetName];
          const sheetJson = xlsx.utils.sheet_to_json(rawSheet, {
            header: 1,
            raw: false,
          }) as (number | string)[][];

          const sheet = workbook.insertSheet(sheetName);
          const rowCount = sheetJson.length;
          const colCount = rowCount > 0 ? sheetJson[0].length : 0;
          sheet.getRange(0, 0, rowCount, colCount).setValues(sheetJson);

          if (workbookData.SheetNames.indexOf(sheetName) === 0) {
            workbook.setActiveSheet(sheet.getSheetId());
          }
        } catch (sheetError) {
          console.error(`导入工作表 "${sheetName}" 出错:`, sheetError);
          ElMessage.error(`导入工作表 "${sheetName}" 失败`);
        }
      }

      input.value = '';
      ElMessage.success('导入完成 ✅');
    } catch (error) {
      console.error('导入失败:', error);
      ElMessage.error('导入失败，请检查文件内容');
    }
  });

  if (file?.name.endsWith('.csv')) {
    file
      ?.text()
      .then((text) => {
        // 处理 CSV 文本内容
        console.error(text);
      })
      .catch(() => {
        ElMessage.error('读取 CSV 文件失败');
      });
  } else if (file?.name.endsWith('.xls') || file?.name.endsWith('.xlsx')) {
    file
      ?.arrayBuffer()
      .then((buffer) => {
        // 处理 Excel 数据缓冲区
        console.error(buffer);
      })
      .catch(() => {
        ElMessage.error('读取 Excel 文件失败');
      });
  } else {
    ElMessage.error('请上传 .csv 或 .xlsx/.xls 格式的文件');
  }
};

const triggerFileInput = () => {
  const fileInput = document.querySelector('#fileInput') as HTMLInputElement;
  fileInput.click();
};
// 拖动过程中
const onMouseMove = (e: MouseEvent) => {
  if (isDragging.value) {
    const delta = e.clientX - startX.value;
    leftPanelWidth.value = Math.max(100, leftPanelWidth.value + delta); // 限制最小宽度
    startX.value = e.clientX;
  }
};

// 结束拖动
const onMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);

  // 通知地图大小更新
  mapInstance?.resize();
};

// 开始拖动
const onMouseDown = (e: MouseEvent) => {
  isDragging.value = true;
  startX.value = e.clientX;
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
};

// 初始化 Mapbox
const initMap = () => {
  if (!mapContainer.value) return;

  mapboxgl.accessToken =
    'pk.eyJ1IjoibmluamFhIiwiYSI6ImNsYXYzd3JwaDAyMGwzdm44ZmI3M212eHQifQ.h_dGMMOvQXNfmheNd0_j8A';

  mapInstance = new mapboxgl.Map({
    container: mapContainer.value,
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [118.916_507, 32.113_575],
    zoom: 10,
  });
};
onMounted(async () => {
  await nextTick();
  if (!container.value || !mapContainer.value) return;

  // 初始化 Univer（数据表格）
  const { univer, univerAPI } = createUniver({
    locale: LocaleType.EN_US,
    locales: {
      [LocaleType.EN_US]: merge({}, UniverPresetSheetsCoreEnUS),
    },
    theme: defaultTheme,
    presets: [
      UniverSheetsCorePreset({
        container: container.value,
      }),
    ],
  });

  univerAPI.createWorkbook({
    name: '数据表格',
    worksheetCount: 0,
  });

  univerInstance = univer;
  univerAPIInstance = univerAPI;

  // 初始化 Mapbox 地图
  initMap();
});
</script>

<template>
  <div class="flex h-full w-full">
    <!-- 左侧面板 -->
    <div
      class="flex-none border-r bg-gray-100 p-2"
      :style="{ width: `${leftPanelWidth}px` }"
    >
      <button
        @click="triggerFileInput"
        class="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
      >
        导入Excel/CSV
      </button>
      <input
        id="fileInput"
        type="file"
        accept=".xlsx,.xls,.csv"
        @change="importFile"
        class="hidden"
      />
      <div ref="container" class="mt-2 flex-1" style="height: 100%"></div>
    </div>

    <!-- 可调节分隔条 -->
    <div
      class="cursor-ew-resize bg-gray-300"
      @mousedown="onMouseDown"
      style="width: 10px"
    ></div>

    <!-- 右侧地图面板 -->
    <div class="map-container flex-1 bg-gray-200" ref="mapContainer"></div>
  </div>
</template>

<style scoped>
/* 可调节区域 */
.cursor-ew-resize {
  width: 10px;
  height: 100%;
  cursor: ew-resize;
}

/* 设置地图容器的固定高度 */
.map-container {
  height: 100%; /* 或者使用固定高度，比如 500px */
}
</style>
